<script setup>
import {ref, watch,defineEmits} from "vue";
import {useCounterStore} from "@/stores/counter.js"

const counterStore = useCounterStore()

let activeIndex = ref(null)

let ChartHistory=ref([])

let AllHistoryMessage=null

watch(()=>counterStore.isShowAIHostory,async () => {
  if (counterStore.isShowAIHostory === false) {
    return
  }
  ChartHistory.value = []
  let aiChartHistory = localStorage.getItem('AiChartHistory');
  let messages = JSON.parse(aiChartHistory)
  if (messages.length === 0) {
    ChartHistory.value.push({
      user: '暂无对话记录',
      ai: ''
    })
    return;
  }
  AllHistoryMessage=messages
  for (let i = 0; i < messages.length; i++) {
    if (messages[i].length !== 0) {
      ChartHistory.value.push({
        user: messages[i][0].content.length >= 15 ? messages[i][0].content.slice(0, 15) + '...' : messages[i][0].content,
        ai: messages[i][1].content.length >= 30 ? messages[i][1].content.slice(0, 30) + '...' : messages[i][1].content,
      })
    }
  }


},{immediate:true})


const emit = defineEmits(['messageSent']);
function openHistoryChat(index){
  let message=AllHistoryMessage[index]
  emit('messageSent', message);
}

</script>

<template>
<div class="History"
     v-for="(item,index) in ChartHistory"
     :key="index"
     @mouseenter="activeIndex = index"
     @mouseleave="activeIndex = null"
     :style="{ backgroundColor: activeIndex === index ? '#f2eded' : 'white' }"
     @click="openHistoryChat(index)"
>
  <h2>{{item.user}}</h2>
  <div>{{item.ai}}</div>
</div>
</template>

<style scoped>
.History{
  margin-bottom: 5px;
  padding: 10px;
  cursor: pointer;
}
h2{
  margin: 0;
  font-size: 17px;
}
.History div:nth-child(2){
  font-size: 14px;
}
</style>